package com.quanyan.activity.init;


import com.quanyan.common.annotation.TargetMethod;
import com.quanyan.common.annotation.TargetService;

import com.quanyan.common.vo.MethodVo;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @Author Hugo.Wwg
 * @Since 2016-05-04
 */
@Component
public class InvokeTargetInit implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    public static Map<String, MethodVo> invokeTargetMap;

    static {
        invokeTargetMap = new ConcurrentHashMap<>();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String, Object> controllerMap = event.getApplicationContext().getBeansWithAnnotation(TargetService.class);
        for (String key : controllerMap.keySet()) {
            Object bean = controllerMap.get(key);
            Method[] methods = bean.getClass().getDeclaredMethods();
            if (methods == null) {
                continue;
            }
            for (Method m : methods) {
                if (m.isAnnotationPresent(TargetMethod.class)) {
                    String command = m.getAnnotation(TargetMethod.class).value();
                    MethodVo value = new MethodVo();
                    value.setTargetBean(bean);
                    value.setTargetMethod(m);
                    invokeTargetMap.put(command, value);
                }
            }
        }
    }
}
